//
//  Messae.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/12/21.
//

import Foundation

class MessageHelper {
    static let shared = MessageHelper()
   let vm = ViewModel.shared

    private init() {
        logger.info("MessageHelper init.")
    }

   func parse(num: Int, content str: String) -> Void {
        do {
            let decoder = JSONDecoder()
            let contentBase = try decoder.decode(APIResponse.self, from: Data(str.utf8))
            if (contentBase.cmd == "MESSAGE") {
                let contentMessage = try decoder.decode(WebSocketMessageBaseResult.self, from: Data(str.utf8))
                if contentMessage.type == "text" {
                    let contentMessageText = try decoder.decode(WebSocketMessageTextResult.self, from: Data(str.utf8))
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        for m in contentMessageText.contents {
                            if m.type == "text" {
                               var textContent = contentMessageText.content
                               if  let shortMessageCode = contentMessageText.phraseCode  {
                                  if !shortMessageCode.isEmpty && shortMessageCode != "null" {
                                     print("[Socket] [Message] [Phrase] code: \(shortMessageCode)")
                                     textContent = self.vm.getShortMessageContent(code: shortMessageCode)
                                  }
                               }
                               let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageText.from, name: "司机", openId: contentMessageText.from!, type: .Driver), text: textContent, type: .text, voice: nil, video: nil,url:nil, phraseCode: "")
                                logger.info("message text:\(message)")
                               let order = CarOrder.shared
                               if !order.isExistMessage(num: num, type: .text, message: contentMessageText.content!) {
                                  CarOrder.shared.messages.append(message)
                               }
                            }
                        }
                        CarOrder.shared.save()
                    }
                } else if contentMessage.type == "image" {
                    let contentMessageImage = try decoder.decode(WebSocketMessageMediaResult.self, from: Data(str.utf8))
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        for m in contentMessageImage.contents {
                            if m.type == "image" {
                                let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageImage.from, name: "司机", openId: contentMessageImage.from!, type: .Driver), text: nil, type: .image, voice: nil, video: nil,url:m.url, phraseCode: "")
                                logger.info("message image:\(message)")
                               let order = CarOrder.shared
                               if !order.isExistMessage(num: num, type: .image, message: m.url) {
                                  CarOrder.shared.messages.append(message)
                               }
                            }
                        }
                        CarOrder.shared.save()
                    }
                } else if contentMessage.type == "voice" {
                    let contentMessageImage = try decoder.decode(WebSocketMessageMediaResult.self, from: Data(str.utf8))
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        for m in contentMessageImage.contents {
                            if m.type == "voice" {
                                let message = Message(createAt: Double(Date().secondsSince1970), image: nil, sender: Member(identifier: contentMessageImage.from, name: "司机", openId: contentMessageImage.from!, type: .Driver), text: nil, type: .voice, voice: nil, video: nil,url:m.url, phraseCode: "")
                                logger.info("message voice:\(message)")
                               let order = CarOrder.shared
                               if !order.isExistMessage(num: num, type: .voice, message: m.url) {
                                  CarOrder.shared.messages.append(message)
                               }
                            }
                        }
                        CarOrder.shared.save()
                    }
                }

                if CarOrder.shared.messages.count > 0 && !ViewModel.shared.inChat {
                    DispatchQueue.main.sync {
                        let notice = Notification(name: .newMessage,object: nil,userInfo:nil)
                        NotificationCenter.default.post(notice)
                    }

                }
            }
        } catch {
            print("\(error)")
        }
    }
}
